﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data;
using System.Dynamic;
using SaturniLibrary.Utility;
using SaturniLibrary.Office;
using Eleanor.BLL;
using System.Drawing;
using Microsoft.VisualBasic;
using Eleanor.Website.Utility;
using Newtonsoft.Json;

namespace Eleanor.Website.Areas.Admin.Controllers
{
    public class PaintingController : Controller
    {
        protected PaintingBLL paintingBLL = new PaintingBLL();

        public ActionResult List()
        {
            string keyword = Request.QueryString["keyword"];
            ViewBag.Keyword = keyword;
            if (string.IsNullOrWhiteSpace(keyword))
            {
                ViewBag.Paintings = new List<dynamic>();
            }
            else
            {
                dynamic condition = new ExpandoObject();
                condition.Keyword = keyword;
                ViewBag.Paintings = paintingBLL.Search(condition, 1, int.MaxValue).PaintingList;
            }

            ViewBag.TopNavigation = "painting";
            ViewBag.SecondNavigation = "paintinglist";
            return View();
        }
 
        public ActionResult Edit(int id)
        {
            dynamic painting = paintingBLL.Get(id);
            ViewBag.Painting = painting;
            ViewBag.TopNavigation = "painting";
            ViewBag.SecondNavigation = "paintinglist";
            ViewBag.Message = Request.QueryString["message"];
            return View();
        }

        //
        // POST: /Admin/Painting/Edit/5

        [HttpPost]
        public ActionResult DoEdit(int id)
        {
            try
            {
                dynamic painting = paintingBLL.Get(id);
                painting.Title = Request.Form["title"].Trim();
                painting.Description = Request.Form["description"];
                painting.Subjects = Request.Form["subject"];
                painting.Authorships = Request.Form["authorship"];
                painting.Tags = Request.Form["tag"];
                painting.Frames = int.Parse(Request.Form["frames"]);
                painting.HandEnable = StringNormalize.IsTrueSynonym(Request.Form["handenable"]);
                painting.PrinterEnable = StringNormalize.IsTrueSynonym(Request.Form["printerenable"]);
                paintingBLL.Update(painting);
                return Redirect("/admin/painting/edit/" + id + "?message=" + HttpUtility.UrlEncode("修改成功"));
            }
            catch
            {
                return Redirect("/admin/painting/edit/" + id + "?message=" + HttpUtility.UrlEncode("修改失败"));
            }
        }

        //
        // GET: /Admin/Painting/Delete/5
 
        public ActionResult Hottest()
        {
            ViewBag.TopNavigatin = "Painting";
            ViewBag.SecondNavigatin = "paintinghot";
            List<dynamic> hosttestList = paintingBLL.GetAllHottestPaintings();
            string hosttestString = "";
            if (hosttestList.Count > 0)
            {
                foreach (dynamic hosttest in hosttestList)
                {
                    hosttestString = hosttestString + hosttest.PaintingNumber + ",";
                }
                hosttestString = hosttestString.TrimEnd(',');
            }
            ViewBag.HosttestString = hosttestString;
            return View();
        }

        [HttpPost]
        public ActionResult UpdateHottest()
        {
            string hottest = Request.Form["hottest"];
            dynamic result = new ExpandoObject();
            try
            {
                paintingBLL.ImprotHottestPainting(hottest);
                result.status = true;
            }
            catch (Exception)
            {
                result.status = false;
            }
            return Content(JsonConvert.SerializeObject(result));
        }

        public ActionResult Import()
        {
            ViewBag.TopNavigation = "function";
            ViewBag.SecondNavigation = "paintingimport";
            return View();
        }

        [HttpPost]
        public ActionResult ImportExcel()
        {
            Stream fs = Request.Files[0].InputStream;
            DataTable paintingDataTable = NPOIExcel.RenderDataTableFromExcel(fs, 0, 0, true);
            fs.Close();
            dynamic result = new ExpandoObject();
            List<dynamic> paintingList = new List<dynamic>();
            foreach (DataRow dataRow in paintingDataTable.Rows)
            {
                dynamic painting = new ExpandoObject();
                painting.PaintingNumber = dataRow["PaintingNumber"].ToString();
                painting.Title = dataRow["Title"].ToString().Trim();
                painting.Authorships = StringNormalize.ReviseChineseComma(dataRow["Authorships"].ToString());
                painting.Subjects = StringNormalize.ReviseChineseComma(dataRow["Subjects"].ToString());
                painting.Tags = StringNormalize.ReviseChineseComma(dataRow["Tags"].ToString()).ToLower();
                painting.HandEnable = StringNormalize.IsTrueSynonym(dataRow["HandEnable"].ToString());
                painting.PrinterEnable = StringNormalize.IsTrueSynonym(dataRow["PrinterEnable"].ToString());
                int frames = 0;
                if (!dataRow["Frames"].Equals(DBNull.Value))
                {
                    int.TryParse(dataRow["Frames"].ToString(), out frames);
                }
                painting.Frames = frames;
                paintingList.Add(painting);
            }
            result.ErrorPaintingList = new List<dynamic>();
            foreach (dynamic painting in paintingList)
            {
                try
                {
                    paintingBLL.Import(painting);
                }
                catch (System.Exception ex)
                {
                    result.ErrorPaintingList.Add(painting);
                }
            }
            //return result;
            return new RedirectResult("/admin/painting/import");
        }

        [HttpPost]
        public ActionResult UploadZip()
        {
            string rootFolder = Server.MapPath("/Temp");
            string tempId = Guid.NewGuid().ToString("N");
            string tempFolder = Path.Combine(rootFolder, tempId);
            string zipFileName = Path.Combine(rootFolder, tempId + ".zip");
            //保存临时文件
            Request.Files[0].SaveAs(zipFileName);
            //解压到临时文件夹
            ZipHelper.UnZip(zipFileName, tempFolder, "", true);
            //复制文件，打水印
            string galleryFolder = Server.MapPath("/Gallery");
            Font font = new Font("Times New Roman", 24.0f);
            string watermarkText = "www.1st-canvas-art.com";
            Color frontColor = Color.White;
            DirectoryInfo folder = new DirectoryInfo(tempFolder);
            FileInfo[] fileInfos = folder.GetFiles("*.jpg", SearchOption.AllDirectories);
            foreach (FileInfo file in fileInfos)
            {
                if (file.Name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
                {
                    string paintingNumber = file.Name.ToLower().Replace(".jpg", "");
                    int paintingId = paintingBLL.CreateSimplePainting(paintingNumber);
                    string folderPath = paintingBLL.GetVirtualFolderPath(paintingId);
                    Stream stream = ImageWatermark.DrawImage(file.FullName, watermarkText, font, frontColor, WatermarkPosition.MiddleCenter);
                    string outputFolder = Path.Combine(galleryFolder, paintingBLL.GetLocalFolderPath(paintingId));
                    if (!Directory.Exists(outputFolder))
                    {
                        FileSystem.MkDir(outputFolder);
                    }
                    string outputFileName = Path.Combine(outputFolder, file.Name);
                    if (System.IO.File.Exists(outputFileName))
                    {
                        System.IO.File.Delete(outputFileName);
                    }
                    Stream outputStream = System.IO.File.OpenWrite(outputFileName);
                    byte[] buffer = new byte[8 * 1024];
                    int len;
                    while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outputStream.Write(buffer, 0, len);
                    }    
                    //更新Painting.ImageUrl
                    dynamic painting = paintingBLL.GetPainting(paintingNumber);
                    painting.ImageUrl = "/Gallery" + folderPath + "/" + file.Name;
                    paintingBLL.Update(painting);
                    stream.Close();
                    outputStream.Close();
                }
            }
            //删除临时文件夹
            Directory.Delete(tempFolder, true);
            //删除临时文件
            System.IO.File.Delete(zipFileName);
            return new RedirectResult("/admin/painting/import");
        }

        public ActionResult Export()
        {
            ViewBag.TopNavigation = "function";
            ViewBag.SecondNavigation = "paintingexport";
            return View();
        }

        [HttpPost]
        public ActionResult ExportExcel()
        {
            string paintingNumbers = Request.Form["paintings"];
            if (string.IsNullOrWhiteSpace(paintingNumbers))
            {
                return new EmptyResult();
            }
            paintingNumbers = StringNormalize.ReviseChineseComma(paintingNumbers.Trim());

            DataTable dataTable = paintingBLL.GetExportDataTable(paintingNumbers);
            dataTable.Columns.Remove("ImageUrl");
            var exporter = new NpoiExport();
            exporter.ExportDataTableToWorkbook(dataTable, "Painting Information");
            ActionResult actionResult = File(exporter.GetBytes(), "application/vnd.ms-excel", "export.xls");
            exporter.Dispose();
            return actionResult;
        }

        [HttpPost]
        public ActionResult ExportZip()
        {
            
            string paintingNumbers = Request.Form["paintings"];
            if (string.IsNullOrWhiteSpace(paintingNumbers))
            {
                return new EmptyResult();
            }
            paintingNumbers = StringNormalize.ReviseChineseComma(paintingNumbers.Trim());
            DataTable dataTable = paintingBLL.GetExportDataTable(paintingNumbers);

            string rootFolder = Server.MapPath("/Temp");
            string tempId = Guid.NewGuid().ToString("N");
            string tempFolder = Path.Combine(rootFolder, tempId);
            string zipFileName = Path.Combine(rootFolder, tempId + ".zip");
             
            //创建临时文件夹
            Directory.CreateDirectory(tempFolder);

            //复制文件
            foreach (DataRow dataRow in dataTable.Rows)
            {
                string imageUrl = dataRow["ImageUrl"].To<string>();
                if(string.IsNullOrWhiteSpace(imageUrl))
                {
                    continue;
                }
                string source = Server.MapPath(imageUrl);
                string destination = Path.Combine(tempFolder, Path.GetFileName(source));
                System.IO.File.Copy(source, destination, true);
            }

            //压缩
            ZipHelper.ZipFileDirectory(tempFolder, zipFileName);

            //读入内存
            ActionResult actionResult = File(System.IO.File.ReadAllBytes(zipFileName), "application/x-compressed", "export.zip");
            //删除临时文件夹
            Directory.Delete(tempFolder, true);
            //删除压缩包
            System.IO.File.Delete(zipFileName);
            return actionResult;
        }

    }
}
